package com.platform.acl.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.platform.acl.Utils.ExcelUtils;
import com.platform.acl.entity.excel.UserInfo;
import com.platform.acl.listener.ExcelListener;
import com.platform.acl.service.UserRoleService;
import com.platform.common_utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author CZF
 * @since 2022-02-28
 */
@Api(tags = "人员")
@RestController
@RequestMapping("/acl/user-role")
@CrossOrigin
public class UserRoleController {

    @Autowired
    UserRoleService userRoleService;

    //人员列表导入(读excel)
    @ApiOperation(value = "人员列表导入（excel导入）")
    @PostMapping("upload")
    public R upload(MultipartFile file) {
        //如果不是excel文件
        if (!ExcelUtils.isExcel(file)) {
            return R.error().message("上传的文件不符合格式");
        }

        try {
            EasyExcel.read(file.getInputStream(), UserInfo.class, new ExcelListener(userRoleService)).sheet().doRead();
        } catch (Exception e) {
            return R.error().message("上传失败！请检查excel中是否含有已注册的成员");
        }

        return R.ok().message("上传成功！");
    }

    //导出供用户填表的excel模板
    @ApiOperation(value = "导出供用户填表的excel模板")
    @GetMapping("excelTemplate")
    public void excelTemplate(HttpServletResponse response) {

        String fileName = "导入人员信息模板.xlsx";
        OutputStream resStream = ExcelUtils.setResponse(fileName, response);

        //用于生成excel模板                   write方法 ：参数1：指定写到哪个流   参数2：表头信息
        ExcelWriter excelWriter = EasyExcel.write(resStream, UserInfo.class).build();
        //生产一个sheet
        WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
        //往excel中添加sheet
        excelWriter.write(new ArrayList<>(), writeSheet);

        // 千万别忘记finish 会帮忙关闭流(resStream),不关闭流会导致导出的excel有问题
        if (excelWriter != null) excelWriter.finish();

    }

    //人员列表导出(写excel)
    //需要配合前端条件查询加分页来导出
    @ApiOperation(value = "人员列表导出（导出为excel）")
    @GetMapping("download")
    public void download(HttpServletResponse response) {


    }

}

